/*
 * Created on Tue Jul 03 2018 by Ronnie Ren (zhaosong.ren) from Accenture
 *
 * Copyright (c) 2018 DingXin information & technology limited company.
 */

import { ObjectDto } from "./object.dto";
import { SqliteUtil } from "./sqlite.util";
import { ConditionPair } from "./condition-fetch";
import { Observable, Subscriber } from "rxjs";


export class SqliteDbTransction {

  constructor(private sqlite: any, private sqls: Array<string> = []) {

  }

  updateObject<T extends ObjectDto>(dto: T, filterKeyValue: ConditionPair, updatedKeys: Array<string> = []) {
    let tableInfo = dto.table();
    let dbUtil = new SqliteUtil();
    let nonEmptyDataObj = dbUtil.filterEmptyAttr(dto, updatedKeys);


    let whereConditions = dbUtil.whereKeyValues(dto, { and: filterKeyValue });
    let where = dbUtil.whereSplice(whereConditions.and, whereConditions.or);
    let sqlSetValues = dbUtil.conditionSplice(dbUtil.splitAndSplice(dbUtil.splitObj(tableInfo, nonEmptyDataObj)), ',');
    console.warn(`update ${tableInfo.tableName} set ${sqlSetValues} ${where}`);

    this.sqls.push(`update ${tableInfo.tableName} set ${sqlSetValues} ${where}`);
    return this;
  }

  commit(): Observable<boolean> {
    return this.sqls.length > 0 ?  this.observableExecuteBatchSql(this.sqls) : Observable.of(true);
  }

  observableExecuteBatchSql(sqls: Array<string>): Observable<boolean> {

    //
    // TODO if we got performance issue on updating,
    // maybe we could try sqlBatch method on the device below
    //
    //
    // if(this.sqlite.sqlBatch) {
    //   return Observable.create((subscriber: Subscriber<boolean>) => {
    //     console.log(sqls);
    //     this.sqlite.sqlBatch(sqls, (text: string, result: object) => {
    //       // success
    //       console.log(text);
    //       console.log(result);
    //       subscriber.next(true);
    //       subscriber.complete();
    //     }, (text: string, error: object) => {
    //       console.log(text);
    //       subscriber.error(error);
    //     });
    //   });
    // }
    // console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
    console.log("observableExecuteBatchSql save data ---- " + JSON.stringify(sqls));
    return Observable.create((subscirber: Subscriber<boolean>) => {
      this.sqlite.transaction((tx) => {
        sqls.forEach((sql: string) => {
          tx.executeSql(sql);
        });
      },
        (error: object) => {
          console.error(JSON.stringify(error) + "batch update error");
          console.log(sqls);
          subscirber.error(error);
        },
        (success: object) => {
          console.log(success + "batch update success");
          subscirber.next(true);
          subscirber.complete();
        });
    });

  }

}
